import random
import os
import sys
import time


# 猜数字游戏

def check_guess(r: str, g: str):
    r = str(r)
    g = str(g)
    num = len(r)
    a = 0
    b = 0
    for i in range(num):
        if r[i] == g[i]:
            a = a + 1
        else:
            b = b + 1
    print("监测完毕，检测结果是：{}位正确 {}位错误".format(a, b))
    if a == num:
        return True
    else:
        return False


def gues_number():
    while True:
        print("~~~=======猜数字游戏=======~~~")
        while True:
            num_len = input("请输入数字位数：")
            if num_len.isdigit():
                if int(num_len) < 2:
                    print("请输入至少为2的数字")
                else:
                    break
            else:
                print("输入错误，请输入数字位数")
        start_num = '1'
        end_num = '9'
        for i in range(int(num_len) - 1):
            start_num += '0'
            end_num += '9'
        result = str(random.randint(int(start_num), int(end_num)))
        print("~~~=======已生成数字，游戏开始=======~~~")
        count = 1
        while True:
            guess = input("第{}次猜的数字是(q退出)：".format(count))
            if guess == 'q':
                print("游戏结束，程序停止")
                return
            elif guess.isdigit():
                if len(guess) == len(result):
                    status = check_guess(result, guess)
                    if status:
                        print("恭喜您，猜对了，答案是 {}".format(result))
                        print("游戏重新开始")
                        break
                    else:
                        count += 1
                        print("猜错了，请重新输入")
                else:
                    print("需要输入{}位的数字".format(len(result)))
            else:
                print("请输入数字，别输错了，请重新输入")


gues_number()
